﻿using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 自动算滚动层的高
/// 同学们可以想一下应用场景，看看宽怎么算，宽高一起怎么算。
/// </summary>
[RequireComponent(typeof(GridLayoutGroup))]
class ScrollViewAutoContent : MonoBehaviour
{
    GridLayoutGroup _targetLayout;
    RectTransform _rectTransform;

    void Awake()
    {
        _targetLayout = GetComponent<GridLayoutGroup>();
        _rectTransform = GetComponent<RectTransform>();
    }

    void Start()
    {
        Refresh();
    }

    /// <summary>
    /// 调用这个函数时，刷新高
    /// </summary>
    public void Refresh()
    {
        if (_rectTransform.childCount <= 0)
        {
            _rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 0);
            return;
        }

        var h = _targetLayout.cellSize.y * _rectTransform.childCount + _targetLayout.spacing.y * (_rectTransform.childCount - 1);
        _rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, h);
    }
}
